//
//  YWFinishDownloadToPlayController.m
//  videoTest3
//
//  Created by jun peng on 2022/9/26.
//

#import "YWFinishDownloadToPlayController.h"

#import "YWNoContentView2.h"
#import "YWYoukuDetailHeaderView.h"
#import "YWVideoView3.h"

#import "YWLittleWindowVedioView.h"
#import "AppDelegate.h"
#import "YWKLineCheatsClassCell.h"
#import "YWDownloadManager3.h"
#import "YWSectionGroupStatus.h"

#define headerViewHeight (headerViewVedioViewHeight + 0) //+45
#define littleWindowInterval 5

@interface YWFinishDownloadToPlayController ()<UITableViewDelegate,UITableViewDataSource,YWYoukuDetailHeaderViewDelegate,YWVideoView3Delegate,NSURLSessionDelegate,NSURLSessionDownloadDelegate,YWKLineCheatsClassCellDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property(nonatomic,strong)NSMutableArray *statusArray;

@property(nonatomic,weak)YWYoukuDetailHeaderView *headerView;

@property (nonatomic, strong) UIView * vedioBgView; // 播放器BgView
@property (nonatomic, strong) YWVideoView3 * vedioView; // 播放器

//小窗口
@property(nonatomic,strong)YWLittleWindowVedioView *littleWindowVedioView;

//正在播放的头部选播视频
@property(nonatomic,strong)YWKLineCheatsVideoListDataStatus *selectedPlayingHeaderStatus;

//选中列表哪一个的、主要是为了修改列表cell样式用的、和上面的不一样
@property(nonatomic,strong)YWKLineCheatsVideoListDataStatus *selectedListStatus;

//这个手势为了全屏时覆盖和阻止返回手势
@property(nonatomic,strong)UIPanGestureRecognizer *panGesture;

@end

@implementation YWFinishDownloadToPlayController

-(UIPanGestureRecognizer *)panGesture{
    if (_panGesture == nil) {
        
        _panGesture = [[UIPanGestureRecognizer alloc] init];
        
        [self.view addGestureRecognizer:self.panGesture];
    }
    return _panGesture;
}

-(YWLittleWindowVedioView *)littleWindowVedioView{
    if (_littleWindowVedioView == nil) {
        _littleWindowVedioView = [YWLittleWindowVedioView videoView];
        
        _littleWindowVedioView.backgroundColor = [UIColor blackColor];
        
        CGFloat w = Wi/2.5;
        CGFloat h = w/1.5;
        CGFloat y = self.view.height - h - littleWindowInterval - h;
        CGFloat x = Wi - w - littleWindowInterval;
        
        _littleWindowVedioView.frame = CGRectMake(x, y, w, h);
        
        [self.view addSubview:_littleWindowVedioView];
        
        _littleWindowVedioView.hidden = YES;
        
        _littleWindowVedioView.layer.cornerRadius = 5;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(littleWindowVedioViewTap)];
        
        [_littleWindowVedioView addGestureRecognizer:tap];
        
        
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
        [_littleWindowVedioView addGestureRecognizer:pan];
        
        
    }
    return _littleWindowVedioView;
}

-(void)pan:(UIPanGestureRecognizer *)pan{
 
    CGPoint transP = [pan translationInView:self.view];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {

            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            
            self.littleWindowVedioView.center = CGPointMake(self.littleWindowVedioView.centerX + transP.x, self.littleWindowVedioView.centerY + transP.y);
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
           
            if (self.littleWindowVedioView.centerX > Wi/2) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.centerX = Wi - self.littleWindowVedioView.width/2 - littleWindowInterval;
              
                }];
                
            }
            else{
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.centerX = self.littleWindowVedioView.width/2 + littleWindowInterval;
              
                }];
                
            }
            if (self.littleWindowVedioView.y < self.navBar.height + littleWindowInterval) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.y = self.navBar.height + littleWindowInterval;
              
                }];
                
            }
            
            if (self.littleWindowVedioView.y > self.view.height - self.littleWindowVedioView.height - littleWindowInterval - 30) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    self.littleWindowVedioView.y = self.view.height - self.littleWindowVedioView.height - littleWindowInterval - 30;
              
                }];
                
            }
            
           
        }
            break;
            
        default:
            break;
    }
    
    //复位.
    [pan setTranslation:CGPointZero inView:self.view];
    
}

-(NSMutableArray *)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"已下载的视频";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    UIView *headerBgView = [[UIView alloc] init];
    
    YWYoukuDetailHeaderView *headerView = [YWYoukuDetailHeaderView headerView];
    
    self.headerView = headerView;
    [headerView hideToolBar];
    headerView.delegate = self;
    
    [headerBgView addSubview:headerView];
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
           
       make.left.equalTo(headerView.superview).with.offset(0);
       make.right.equalTo(headerView.superview).with.offset(0);
       make.bottom.equalTo(headerView.superview).with.offset(0);
       make.top.equalTo(headerView.superview).with.offset(0);
      
    }];
    
    headerBgView.frame = CGRectMake(0, 0, Wi, headerViewHeight);
    
    self.tableView.tableHeaderView = headerBgView;
    
    // 创建播放器
    self.vedioView = [YWVideoView3 videoView];
    self.vedioView.delegate = self;
    self.vedioBgView = [UIView new];
    [self.tableView addSubview:self.vedioBgView];
    self.vedioBgView.backgroundColor = [UIColor blackColor];
    self.vedioView.backgroundColor = [UIColor blackColor];
    [self.vedioBgView addSubview:self.vedioView];
    self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);
    self.vedioView.frame = self.vedioBgView.bounds;
    
    //指着保存
    self.selectedPlayingHeaderStatus = self.status;
    
    //播放
    YWLog(@"aaa - %@",self.selectedPlayingHeaderStatus.VideoUrl);
    //其实这个判断放在单例Manager好一点
    if (self.status.VideoUrl != nil) {
        self.vedioView.status = self.selectedPlayingHeaderStatus;
        
        [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
            
            [self.vedioView startPlayWithUrl:fullPath withMute:NO];
        } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
            
            [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
        }];
        
        
        
//        [self.vedioView startPlayWithUrl:self.status.VideoUrl withMute:NO];
        
    }
    
    
    [self loadVideoNewData];
    
}


-(void)noContentView2DidClickRefreshBtn:(YWNoContentView2 *)noContentView2{
    
    [self loadVideoNewData];
    
}

-(void)loadVideoNewData{
    //获取数据
    YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
    MJWeakSelf
    [manager getDataTaskArray:^(NSArray * _Nonnull group) {
        
        //假如group的数据有变化、都会走block、从而刷新列表
//        weakSelf.group = group;
//        [weakSelf.tableView reloadData];
//
//        YWSectionGroupStatus *sectionStatus0 = weakSelf.group[0];
        YWSectionGroupStatus *sectionStatus1 = group[1];
        
        NSArray *array = sectionStatus1.statusArray;
        
        
        if (array.count == 0) {
            //这里弄个noCotentView
            [weakSelf.view addSubview:weakSelf.noContentView];
            weakSelf.noContentView.frame = CGRectMake(0, weakSelf.navBar.height, Wi, weakSelf.view.height - weakSelf.navBar.height);
            weakSelf.noContentView.noContentType = YWNoContentView2Type_NoContentButNotConformBtn;
        }
        else{
            //移除noCotentView
            [weakSelf.noContentView removeFromSuperview];
            
            NSMutableArray *mArray = [NSMutableArray array];
            for (YWDownloadStatus3 *status in array) {
                YWKLineCheatsVideoListDataStatus *cheatsStatus = [[YWKLineCheatsVideoListDataStatus alloc] init];
                
                cheatsStatus.Title = status.Title;
                cheatsStatus.PicUrl = status.PicUrl;
                cheatsStatus.Id = status.Id;
                cheatsStatus.VideoUrl = status.VideoUrl;
                cheatsStatus.isNeedHideRedaAndPraiseLabel = YES;
                [mArray addObject:cheatsStatus];
            }
            
            weakSelf.statusArray = mArray;
            [weakSelf.tableView reloadData];
            
        }
    }];
    
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //这里用isPlaying不用isPlaying_containPause
    if (self.vedioView.isPlaying == YES) {  //headerView正在播放中
      
        if (scrollView.contentOffset.y >= headerViewVedioViewHeight) {
            
            //这样就可以保证只执行一次、因为你滚动过程不断掉用continue会造成卡顿的
            if (self.littleWindowVedioView.hidden == YES) {
                
                self.littleWindowVedioView.hidden = NO;
                
                //继续播放不需要判断本地存不存在、原来用fullPath还是videoUrl就用回之前的、也就是self.vedioView.urlString
                [self.littleWindowVedioView continuePlayWithAnthorViewWithUrl:self.vedioView.urlString WithMute:NO];
            }
            
        }
        else{
            
            //这样就可以保证只执行一次、因为你滚动过程不断掉用continue会造成卡顿的
            if (self.littleWindowVedioView.hidden == NO) {
                
                self.littleWindowVedioView.hidden = YES;
                
                //继续播放不需要判断本地存不存在、原来用fullPath还是videoUrl就用回之前的、也就是self.vedioView.urlString
                [self.vedioView continuePlayWithAnthorViewWithUrl:self.vedioView.urlString WithMute:NO];
            }
            
         
        }
    }
}

-(void)littleWindowVedioViewTap{
    
    [self pagerViewScrollToTop];
   
}


- (void)pagerViewScrollToTop{
    
    [self.tableView setContentOffset:CGPointZero animated:YES];
}



-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //强制竖屏
    [self setViewOrientation:UIInterfaceOrientationPortrait];
    
}



- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    //这个无论是不是去横视频界面都去隐藏vedioBgView
    self.vedioBgView.hidden = YES;
    
    [self.vedioView stopPlay];
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWKLineCheatsVideoListDataStatus *dataStatus = self.statusArray[indexPath.row];
    
    YWKLineCheatsClassCell *cell = [YWKLineCheatsClassCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.status = dataStatus;
    return cell;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 105;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self pagerViewScrollToTop];
    
    YWKLineCheatsVideoListDataStatus *status = self.statusArray[indexPath.row];
    
    //这里有可能是点击选播传过来的、所以要保存
    self.selectedPlayingHeaderStatus = status;

    //改变cell样式
    self.selectedListStatus.isSelect = NO;
    status.isSelect = YES;
    self.selectedListStatus = status;
    [self.tableView reloadData];

    self.littleWindowVedioView.hidden = YES;

    self.vedioView.status = self.selectedPlayingHeaderStatus;
    
    
    [YWVideoPlayerManager videoPlayWithKLineCheatsVideoListDataStatus:self.selectedPlayingHeaderStatus canPlayLoacalWithFullPathBlock:^(NSString * _Nonnull fullPath) {
        
        [self.vedioView startPlayWithUrl:fullPath withMute:NO];
    } onlyCanPlayWebWithVideoUrlBlock:^(NSString * _Nonnull videoUrl) {
        
        [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
    }];

   
    
//    [self.vedioView startPlayWithUrl:videoUrl withMute:NO];
    
    

    
    
    [self.tableView addSubview:self.vedioBgView];

    self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);

    self.vedioView.frame = self.vedioBgView.bounds;

    self.vedioBgView.layer.cornerRadius = 0;

    self.vedioBgView.clipsToBounds = YES;

    self.vedioBgView.hidden = NO;
    
    
}


//// ------------

#pragma mark - 横屏模式

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    
}
/**
 *  在此方法中修改布局
 */
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    // 布局
    if(isLanscape)
    {
        
        self.tableView.hidden = YES;
        self.navBar.hidden = YES;
        
        self.view.backgroundColor = [UIColor blackColor];
        self.panGesture.enabled = YES;
        
        
        self.vedioView.bigScaleBtn.selected = YES;
        
        
        if (self.littleWindowVedioView.hidden == YES) { //小窗口不出现就是正在用vedioView
            
            [self.view addSubview:self.vedioBgView];
            
            self.vedioBgView.frame = CGRectMake(0, 0, Wi, He);
            
            self.vedioView.frame = self.vedioBgView.bounds;
            
            self.vedioBgView.layer.cornerRadius = 0;
        }
        else{ //正在使用小窗口
            [self.view addSubview:self.littleWindowVedioView];
            
            self.littleWindowVedioView.frame = CGRectMake(0, 0, Wi, He);
            
            self.littleWindowVedioView.layer.cornerRadius = 0;
            
        }
        
        
    }else
    {
        
        self.tableView.hidden = NO;
        self.navBar.hidden = NO;
        
        self.view.backgroundColor = [UIColor whiteColor];
        self.panGesture.enabled = NO;
        
        //加了这句就可以了、因为你把tableView的frame转换的时候tableView还是以横盘的参考对象、假如你写了layoutIfNeeded它就等你变成了竖屏再以竖屏的tableView为参考对象
        [self.view layoutIfNeeded];
        
        
        self.vedioView.bigScaleBtn.selected = NO;
        
        if (self.littleWindowVedioView.hidden == YES) { //小窗口不出现就是正在用vedioView
            
            //因为就算是headerView的vedioView在播放、竖屏后小窗口的宽高也被改变了、所以这里要重新设置小窗口的宽高
            CGFloat w = Wi/2.5;
            CGFloat h = w/1.5;
            self.littleWindowVedioView.width = w;
            self.littleWindowVedioView.height = h;
            
            [self.tableView addSubview:self.vedioBgView];
            self.vedioBgView.frame = CGRectMake(0, 0, Wi, headerViewVedioViewHeight);
            self.vedioView.frame = self.vedioBgView.bounds;
            
            self.vedioBgView.layer.cornerRadius = 0;
        }
        else{ //正在使用小窗口
            
            CGFloat w = Wi/2.5;
            CGFloat h = w/1.5;
            CGFloat y = self.view.height - h - littleWindowInterval - h;
            CGFloat x = Wi - w - littleWindowInterval;
            
            self.littleWindowVedioView.frame = CGRectMake(x, y, w, h);
            
            [self.view addSubview:_littleWindowVedioView];
            
            self.littleWindowVedioView.layer.cornerRadius = 5;
            
        }
        
        
        
        
        
        
        
        
        
    }


}

//放大/缩小
-(void)videoView:(YWVideoView3 *)videoView didClickBigScaleBtn:(UIButton *)btn{
    
    
//    btn.selected = !btn.selected;
    if (self.vedioView.bigScaleBtn.selected) {
           [self setViewOrientation:UIInterfaceOrientationPortrait];
    }
    else{
        
           [self setViewOrientation:UIInterfaceOrientationLandscapeRight];
    }
}




//强制横屏或竖屏
-(void)setViewOrientation:(UIInterfaceOrientation)orientation{

    if (@available(iOS 16.0, *)) {
        [UIApplication.sharedApplication.keyWindow.rootViewController setNeedsUpdateOfSupportedInterfaceOrientations];
              
              NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
              UIWindowScene *ws = (UIWindowScene *)array[0];
              UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [UIWindowSceneGeometryPreferencesIOS.alloc initWithInterfaceOrientations:1 << orientation];
              [ws requestGeometryUpdateWithPreferences:geometryPreferences
                                          errorHandler:^(NSError * _Nonnull error) {
              }];
//            @try {
//                NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
//                UIWindowScene *ws = (UIWindowScene *)array[0];
//                Class GeometryPreferences = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");
//                id geometryPreferences = [[GeometryPreferences alloc]init];
//
//                if(orientation == UIInterfaceOrientationPortrait) {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskPortrait) forKey:@"interfaceOrientations"];
//                }
//                else {
//                    [geometryPreferences setValue:@(UIInterfaceOrientationMaskLandscapeRight) forKey:@"interfaceOrientations"];
//                }
//
//                SEL sel_method = NSSelectorFromString(@"requestGeometryUpdateWithPreferences:errorHandler:");
//                void (^ErrorBlock)(NSError *err) = ^(NSError *err){
//                      NSLog(@"调用了Block%@",err);
//                };
//                if ([ws respondsToSelector:sel_method]) {
//                    (((void (*)(id, SEL,id,id))[ws methodForSelector:sel_method])(ws, sel_method,geometryPreferences,ErrorBlock));
//                }
//            } @catch (NSException *exception) {
//                NSLog(@"*****************************华丽分割线**************************");
//                NSLog(@"%@",exception);
//            } @finally {
//
//            }
        } else {
            
            if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
                SEL selector = NSSelectorFromString(@"setOrientation:");
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
                [invocation setSelector:selector];
                [invocation setTarget:[UIDevice currentDevice]];
                int val = (int)orientation;
                [invocation setArgument:&val atIndex:2];
                [invocation invoke];

            }

        }
    
    

}

//////

// 本VC可以支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

// 本VC是否支持设备自动旋转
- (BOOL)shouldAutorotate
{
    return YES;
}

/**
 *  当屏幕即将旋转的时候调用
 *  @param toInterfaceOrientation 旋转完毕后的最终方向
 *  @param duration  旋转动画所花费的时间
 */
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    
    //切换屏幕方向时候把videoFunctionView设为透明效果会好点
//    self.videoFunctionView.alpha = 0;

    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {// 横屏

    } else {//竖屏

    }

}

//开始成功代理
-(void)videoViewDidStartPlay:(YWVideoView3 *)videoView{
    
    //让整个程序能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 1;
    
    
}

//停止成功代理
-(void)videoViewDidSotpPlay:(YWVideoView3 *)videoView{
    
    //让整个程序不能旋转
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotate = 0;
    
    
}





@end
